<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/12/19
 * Time: 13:58
 * @link http://www.lmterp.cn
 */

namespace app\common\model;

class PurchaseExchange extends BaseModel
{
    protected $pk = 'exchange_id';

    protected $autoWriteTimestamp = 'datetime';

    protected $insert = ['create_by', 'update_by'];

    protected $update = ['update_by'];

    /**
     * 待处理
     * @var int
     */
    const STATUS_EXCHANGE_WAIT = 0;

    /**
     * 占用库存
     * @var int
     */
    const STATUS_EXCHANGE_LOCK_STOCK = 10;

    /**
     * 待出库
     * @var int
     */
    const STATUS_EXCHANGE_WAIT_OUT = 20;

    /**
     * 已出库
     * @var int
     */
    const STATUS_EXCHANGE_OUT = 30;

    /**
     * 已签收
     * @var int
     */
    const STATUS_EXCHANGE_RECV = 40;

    /**
     * 取消
     * @var int
     */
    const STATUS_EXCHANGE_CANCEL = 50;

    public static $STATUS_EXCHANGE = [
        self::STATUS_EXCHANGE_WAIT => '待处理',
        self::STATUS_EXCHANGE_LOCK_STOCK => '占用库存',
        self::STATUS_EXCHANGE_WAIT_OUT => '待出库',
        self::STATUS_EXCHANGE_OUT => '已出库',
        self::STATUS_EXCHANGE_RECV => '已签收',
        self::STATUS_EXCHANGE_CANCEL => '取消',
    ];

    protected function getStatusAttr($value)
    {
        return isset(self::$STATUS_EXCHANGE[$value]) ? self::$STATUS_EXCHANGE[$value] : $value;
    }

    protected function getPayTypeAttr($value)
    {
        return isset(PurchaseTrack::$PAY_TYPE[$value]) ? PurchaseTrack::$PAY_TYPE[$value] : $value;
    }

    /**
     * 关联仓库
     * @return \think\model\relation\BelongsTo
     * @date 2020/11/07
     * @author longli
     */
    public function warehouse()
    {
        return $this->belongsTo(Warehouse::class);
    }

    /**
     * 关联采购单
     * @return \think\model\relation\BelongsTo
     * @date 2021/01/06
     * @author longli
     */
    public function purchase()
    {
        return $this->belongsTo(Purchase::class);
    }

    /**
     * 关联换货详情
     * @return \think\model\relation\HasMany
     * @date 2020/12/29
     * @author longli
     */
    public function info()
    {
        return $this->hasMany(PurchaseTerpInfo::class, 'ref_id', 'exchange_id')
            ->where("id_type", static::getTable());
    }

    /**
     * 获取换货单
     * @param int|string $sn 换货单id，换货单号
     * @return PurchaseExchange
     * @date 2021/01/11
     * @author longli
     */
    public static function getBySn($sn)
    {
        return static::where("exchange_id", $sn)
            ->whereOr("exchange_sn", trim($sn))
            ->find();
    }
}
